package response

import (
	"carSpider/data"
	goSpider "github.com/Flyits/goSpider/src"
	"github.com/antchfx/htmlquery"
	"strings"
)

func Model(response goSpider.Response, spider *goSpider.Spider) {
	modelList := htmlquery.Find(response.HtmlNode, "//div[@class='brand-list']/div[@class='brand-item']")
	for k, _ := range modelList {
		model := data.Model{}
		model.BrandId = response.Attach.(int)
		model.SubBrandName = htmlquery.FindOne(modelList[k], ".//div[@class='brand-name']/text()").Data
		for _, carList := range htmlquery.Find(modelList[k], ".//div[@class='brand-car']/a") {
			model.ID = 0
			model.Name = strings.Trim(strings.Trim(htmlquery.FindOne(carList, ".//div[@class='car-name']/text()").Data, " "), "\n")
			model.CoverImage = htmlquery.SelectAttr(htmlquery.FindOne(carList, ".//img"), "data-original")
			model.CoverImage = strings.Replace(model.CoverImage, "_4", "_8", -1)

			url := htmlquery.SelectAttr(carList, "href")
			spider.AddJob(goSpider.UrlItem{
				Url:         BaseUrl + url,
				HandlerFunc: Version,
				Attach:      map[string]int{"brandId": model.BrandId, "modelId": modelExists(model)},
			})
		}
	}

}

// 检测
func modelExists(result data.Model) int {
	model := data.Model{}
	data.Db.Where("name = ? AND brand_id = ?", result.Name, result.BrandId).First(&model)
	if data.Db.NewRecord(model) {
		data.Db.Create(&result)
		return result.ID
	}
	return model.ID
}
